<template>
	<StickyHeader />
	<div class="list-page" :style='{}'>
        <div class="breadcrumb-wrapper" style="width: 100%;">
            <div class="bread_view">
                <el-breadcrumb separator="" class="breadcrumb">
                    <el-breadcrumb-item class="second_breadcrumb" v-for="(item,index) in breadList.filter(i => i.name && i.name !== '项目信息')" :key="index">
                        <span class="el-breadcrumb__inner" role="link">{{item.name}}</span>
                    </el-breadcrumb-item>
                </el-breadcrumb>
            </div>
            <div class="back_view" v-if="centerType">
                <el-button class="back_btn" @click="backClick" type="primary">返回</el-button>
            </div>
        </div>
		<el-form :inline="true" :model="searchQuery" class="list_search">
			<div class="search_view">
				<div class="search_label">
					项目名称：
				</div>
				<div class="search_box">
					<el-input class="search_inp" v-model="searchQuery.xiangmumingcheng" placeholder="请输入项目名称关键词"
						clearable @clear="handleClear('xiangmumingcheng')" @keyup.enter="searchClick">
						<template #prefix>
							<el-icon><Search /></el-icon>
						</template>
					</el-input>
				</div>
			</div>
			<div class="search_view">
				<div class="search_label">
					项目阶段：
				</div>
				<div class="search_box">
					<el-select
						class="search_sel"
						clearable
						v-model="searchQuery.xiangmujieduan" 
						placeholder="请选择项目阶段"
						@clear="handleClear('xiangmujieduan')"
						@change="handleCategoryChange">
						<el-option v-for="item in xiangmujieduanLists" :label="item" :value="item"></el-option>
					</el-select>
				</div>
			</div>
			<div class="search_btn_view">
				<el-button 
					class="search_btn" 
					type="primary" 
					:loading="searchLoading" 
					@click="searchClick"
					:icon="Search">
					{{ searchLoading ? '搜索中...' : '搜索' }}
				</el-button>
				<el-button class="add_btn" type="success" v-if="!(user?.role === '导师' || context?.$toolUtil.storageGet('frontRole') === '导师')" @click="addClick">+ 新增</el-button>
			</div>
		</el-form>
		<div class="page_list">
			<!-- 这里原本有公告信息提示，已删除 -->
			
			<!-- 空结果提示 -->
			<el-empty v-if="list.length === 0" description="暂无符合条件的项目信息"></el-empty>
			
			<!-- 现有列表展示 -->
			<div class="data_box" v-else>
				<el-table
					:data="list"
					style="width: 100%"
					@row-click="(row) => detailClick(row.id)"
					:header-cell-style="{
						background: '#f5f7fa',
						color: '#606266',
						fontWeight: 'bold',
						textAlign: 'center'
					}"
					:cell-style="{textAlign: 'center'}"
				>
					<el-table-column label="图片" align="center" width="100">
						<template #default="scope">
							<el-image 
								style="width: 60px; height: 60px; border-radius: 4px;"
								:src="scope.row.xiangmutupian ? 
									(scope.row.xiangmutupian.substr(0,4)=='http' ? scope.row.xiangmutupian : $config.url + scope.row.xiangmutupian.split(',')[0]) 
									: ''" 
								fit="cover"
								@click.stop="preViewClick(scope.row.xiangmutupian.substr(0,4)=='http' ? scope.row.xiangmutupian : $config.url + scope.row.xiangmutupian.split(',')[0])">
							</el-image>
						</template>
					</el-table-column>
					<el-table-column label="项目名称" align="center">
						<template #default="scope">
							<div class="project-info">
								<span class="project-name" :class="{'highlight-keyword': isSearchActive && searchQuery.xiangmumingcheng && scope.row.xiangmumingcheng.toLowerCase().includes(searchQuery.xiangmumingcheng.toLowerCase())}">
									{{ scope.row.xiangmumingcheng }}
								</span>
								<el-tag v-if="centerType" :type="scope.row.sfsh === '是' ? 'success' : (scope.row.sfsh === '否' ? 'danger' : 'warning')" size="small" style="margin-left: 10px;">
									{{ scope.row.sfsh === '是' ? '已通过' : (scope.row.sfsh === '否' ? '未通过' : '待审核') }}
								</el-tag>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="xiangmufenlei" label="项目类型" align="center"></el-table-column>
					<el-table-column prop="xiangmujieduan" label="项目阶段" align="center">
						<template #default="scope">
							<span :class="{'highlight-category': isSearchActive && searchQuery.xiangmujieduan && scope.row.xiangmujieduan === searchQuery.xiangmujieduan}">
								{{ scope.row.xiangmujieduan }}
							</span>
						</template>
					</el-table-column>
					<el-table-column label="项目详情" align="center">
						<template #default="scope">
							<span class="project-detail">{{ truncateText(scope.row.xiangmuxiangqing || '暂无详情', 50) }}</span>
						</template>
					</el-table-column>
				</el-table>
				
				<el-pagination
					background 
					:layout="layouts.join(',')"
					:total="total" 
					:page-size="listQuery.limit"
                    v-model:current-page="listQuery.page"
					prev-text="上一页"
					next-text="下一页"
					:hide-on-single-page="false"
					:style='{}'
					@size-change="sizeChange"
					@current-change="currentChange"/>
			</div>
		</div>
		<el-dialog v-model="preViewVisible" width="800px" top="5vh" destroy-on-close align-center>
			<div style="padding: 20px; display: flex; justify-content: center; align-items: center; height: 100%;">
				<img :src="preViewUrl" style="width: 100%; max-height: 70vh; object-fit: contain; border-radius: 8px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);" alt="">
			</div>
		</el-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance,
		nextTick,
        computed,
		watch
	} from 'vue';
	import {
		useRoute,
		useRouter
	} from 'vue-router';
    import {
        useStore
    } from 'vuex';
    import { Search } from '@element-plus/icons-vue';
    import StickyHeader from '@/components/StickyHeader.vue'
    const store = useStore()
    const user = computed(()=>store.getters['user/session'])
	const context = getCurrentInstance()?.appContext.config.globalProperties;
	const router = useRouter()
	const route = useRoute()
	//基础信息
	const tableName = 'xiangmuxinxi'
	const formName = '项目信息'
	//基础信息
	const breadList = ref([{
		name: formName
	}])
	const list = ref([])
	const listQuery = ref({
		page: 1,
		limit: Number(12)
	})
	const total = ref(0)
	const listLoading = ref(false)
	//权限验证
	const btnAuth = (e,a)=>{
		if(centerType.value){
			return context?.$toolUtil.isBackAuth(e,a)
		}else{
			return context?.$toolUtil.isAuth(e,a)
		}
	}
	const addClick = () => {
		router.push('/index/xiangmuxinxiAdd')
	}
	//判断是否从个人中心跳转
	const centerType = ref(false)
//返回
const backClick = () => {
	// 清除保存的状态
	localStorage.removeItem('xiangmuxinxi_centerType')
	localStorage.removeItem('xiangmuxinxi_fuzerenzhanghao')
	router.push(`/index/${context?.$toolUtil.storageGet('frontSessionTable')}Center`)
}
	//搜索
	const searchQuery = ref({})
	//下拉列表
	const xiangmujieduanLists = ref([])
	const getxiangmujieduanLists = () => {
		xiangmujieduanLists.value = '萌创期,初创期,孵创期'.split(',')
	}
	getxiangmujieduanLists()
	
	// 添加搜索加载状态
	const searchLoading = ref(false)
	const isSearchActive = ref(false)
	
	// 优化清除搜索条件的函数
	const handleClear = (field) => {
		if (field) {
			searchQuery.value[field] = '';
			// 对于分类选择，立即触发搜索
			if (field === 'xiangmujieduan') {
				searchClick();
			}
		}
	}
	
	// 优化分类变化处理函数
	const handleCategoryChange = () => {
		// 分类变化后自动搜索
		searchClick();
	}
	
	// 优化清除所有搜索条件的函数
	const clearSearch = () => {
		searchQuery.value = {};
		listQuery.value.page = 1;
		searchLoading.value = true;
		getList();
	}
	
	// 修改高亮关键词函数，增强匹配效果
	const highlightKeyword = (text, keyword) => {
		if (!keyword || !text) return text;
		try {
			// 不区分大小写
			const regex = new RegExp(`(${keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
			return text.replace(regex, '<span class="highlight-keyword">$1</span>');
		} catch (e) {
			return text;
		}
	}
	
	// 检查项是否匹配搜索条件的函数
	const isItemMatched = (item) => {
		// 如果没有搜索条件，所有项都匹配
		if (!searchQuery.value.xiangmumingcheng && !searchQuery.value.xiangmujieduan) {
			return true;
		}
		
		// 检查名称匹配
		const nameMatch = !searchQuery.value.xiangmumingcheng || 
			(item.xiangmumingcheng && item.xiangmumingcheng.toLowerCase().includes(searchQuery.value.xiangmumingcheng.toLowerCase()));
		
		// 检查阶段匹配
		const jieduanMatch = !searchQuery.value.xiangmujieduan || 
			(item.xiangmujieduan === searchQuery.value.xiangmujieduan);
		
		// 同时满足名称和阶段条件才匹配
		return nameMatch && jieduanMatch;
	}
	
	const searchClick = () => {
		searchLoading.value = true;
		listQuery.value.page = 1
		getList()
	}
	//分页
	const layouts = ref(["total","prev","pager","next","sizes","jumper"])
	const sizeChange = (size) => {
		listQuery.value.limit = size
		getList()
	}
	const currentChange = (page) => {
		listQuery.value.page = page
		getList()
	}
	//分页
	//列表
	const getList = () => {
		listLoading.value = true
		searchLoading.value = true
		let params = JSON.parse(JSON.stringify(listQuery.value))
		
		// 保存原始搜索条件用于前端过滤
		const nameKeyword = searchQuery.value.xiangmumingcheng?.trim().toLowerCase() || '';
		const jieduanKeyword = searchQuery.value.xiangmujieduan?.trim() || '';
		
		// 修改为获取所有数据，前端进行过滤
		if(searchQuery.value.xiangmumingcheng && searchQuery.value.xiangmumingcheng!=''){
			params.xiangmumingcheng = '%' + searchQuery.value.xiangmumingcheng + '%'
		}
		if(searchQuery.value.xiangmujieduan && searchQuery.value.xiangmujieduan!=''){
			params.xiangmujieduan = searchQuery.value.xiangmujieduan
		}
        params['sort'] = 'tijiaoshijian';
        params['order'] = 'desc';
		if(!centerType.value){
			// 在前台列表页面，只显示审核通过的项目
			params['sfsh'] = '是';
		} else {
			// 在个人中心页面，显示当前用户的所有项目（包括待审核的）
			if (searchQuery.value.fuzerenzhanghao) {
				params['fuzerenzhanghao'] = searchQuery.value.fuzerenzhanghao;
			} else if (user.value && user.value.xuehao) {
				params['fuzerenzhanghao'] = user.value.xuehao;
			}
		}
		
		// 如果有搜索条件，则移除后端搜索参数，改为前端过滤
		if(nameKeyword || jieduanKeyword) {
			delete params.xiangmumingcheng;
			delete params.xiangmujieduan;
		}
		
		context?.$http({
			url: `${tableName}/${centerType.value?'page':'list'}`,
			method: 'get',
			params: params
		}).then(res => {
			listLoading.value = false
			searchLoading.value = false // 搜索完成，关闭加载动画
			
			if (res.data && res.data.data) {
				const allItems = res.data.data.list || [];
				
				// 前端过滤数据
				if(nameKeyword || jieduanKeyword) {
					// 搜索状态
					isSearchActive.value = true;
					
					// 根据条件过滤
					list.value = allItems.filter(item => {
						const nameMatches = !nameKeyword || 
							(item.xiangmumingcheng && 
							item.xiangmumingcheng.toLowerCase().includes(nameKeyword));
							
						const jieduanMatches = !jieduanKeyword || 
							item.xiangmujieduan === jieduanKeyword;
							
						// 两个条件都满足才显示
						return nameMatches && jieduanMatches;
					});
					
					// 更新总数（只显示过滤后的数量）
					total.value = list.value.length;
				} else {
					// 没有搜索条件，显示全部数据
					list.value = allItems;
					total.value = Number(res.data.data.total) || 0;
					isSearchActive.value = false;
				}
				
				// 如果不是个人中心页面，再次过滤掉待审核的项目（双重保险）
				if (!centerType.value) {
					list.value = list.value.filter(item => item.sfsh === '是');
				}
				
				// 搜索结果为空时显示提示
				if ((nameKeyword || jieduanKeyword) && list.value.length === 0) {
					context?.$toolUtil.message('未找到符合条件的项目信息', 'info')
				}
			}
		}).catch(error => {
			listLoading.value = false
			searchLoading.value = false // 发生错误时也关闭加载动画
			console.error('获取列表数据失败:', error)
			context?.$toolUtil.message('获取数据失败', 'error')
		})
	}
	const detailClick = (id) => {
		router.push(`${tableName}Detail?id=` + id + (centerType.value?'&&centerType=1':''))
	}
	//下载文件
	const download = (file) =>{
		if(!file){
			context?.$toolUtil.message('文件不存在','error')
		}
		const a = document.createElement('a');
		a.style.display = 'none';
		a.setAttribute('target', '_blank');
		file && a.setAttribute('download', file);
		a.href = context?.$config.url + file;
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}
	// 截断文本
	const truncateText = (text, maxLength) => {
		if (!text) return '暂无详情';
		
		// 去除HTML标签
		const cleanText = text.replace(/<\/?[^>]+(>|$)/g, "");
		
		if (cleanText.length > maxLength) {
			return cleanText.slice(0, maxLength) + '...';
		}
		return cleanText;
	}
	// 查看大图
	const preViewUrl = ref('')
	const preViewVisible = ref(false)
	const preViewClick = (url) =>{
		preViewUrl.value = url
		preViewVisible.value = true
	}
// 监听路由变化
watch(() => route.query.centerType, (newVal) => {
    if(newVal) {
        centerType.value = true
        localStorage.setItem('xiangmuxinxi_centerType', 'true')
        if(user.value && user.value.xuehao) {
            searchQuery.value.fuzerenzhanghao = user.value.xuehao
            localStorage.setItem('xiangmuxinxi_fuzerenzhanghao', user.value.xuehao)
        }
    } else {
        centerType.value = false
        localStorage.removeItem('xiangmuxinxi_centerType')
        localStorage.removeItem('xiangmuxinxi_fuzerenzhanghao')
        delete searchQuery.value.fuzerenzhanghao
    }
    getList()
})

const init = async() => {
	const savedCenterType = localStorage.getItem('xiangmuxinxi_centerType')
	const savedFuzerenzhanghao = localStorage.getItem('xiangmuxinxi_fuzerenzhanghao')
	
	// 先设置centerType状态
	if(savedCenterType === 'true') {
		centerType.value = true
	}
	
	// 恢复负责人账号
	if(savedFuzerenzhanghao) {
		searchQuery.value.fuzerenzhanghao = savedFuzerenzhanghao
	}
	
	// 检查URL参数（优先级最高）
	if(route.query.centerType){
		centerType.value = true
		localStorage.setItem('xiangmuxinxi_centerType', 'true')
	}
	
	// 确保用户已登录
	await new Promise(resolve => {
		const checkUser = () => {
			if(user.value) {
				resolve()
			} else {
				setTimeout(checkUser, 100)
			}
		}
		checkUser()
	})
	
	// 检查用户是否登录
	if(centerType.value) {
		if(!user.value) {
			centerType.value = false
			localStorage.removeItem('xiangmuxinxi_centerType')
		}
	}
	
	// 如果是从个人中心进入，设置负责人账号筛选条件
	if(centerType.value && user.value && user.value.xuehao) {
		searchQuery.value.fuzerenzhanghao = user.value.xuehao
		localStorage.setItem('xiangmuxinxi_fuzerenzhanghao', user.value.xuehao)
	}
	
	xiangmujieduanLists.value = '萌创期,初创期,孵创期'.split(',')
	getList()
}
	init()
</script>
<style lang="scss" scoped>
.list-page {
  width: 100%;
  max-width: 1800px;
  margin: 0 auto;
  padding: 0 40px;
  font-size: 20px;
  background: #fff;
}
.page_list {
  font-size: 20px;
}
.data_box {
  font-size: 20px;
}
:deep(.el-table__header),
:deep(.el-table__row) {
  font-size: 20px;
}
:deep(.el-table__cell) {
  font-size: 20px;
}
:deep(.el-table__header .el-table__cell) {
  font-size: 21px;
  font-weight: bold;
}
:deep(.el-table__body .el-table__cell) {
  font-size: 20px;
}
// 调整表格图片尺寸更大
:deep(.el-image) {
  width: 100px !important;
  height: 100px !important;
}
	// 返回盒子
	.back_view {
		// 返回按钮
		.back_btn {
		}
		// 返回按钮-悬浮
		.back_btn:hover {
		}
	}
	
	// 项目信息样式
	.project-info {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 10px;
		
		.project-name {
			font-weight: bold;
			color: #303133;
		}
	}
	
	.project-detail {
		display: inline-block;
		width: 200px;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	
	// 表格行鼠标悬停样式
	:deep(.el-table__row) {
		cursor: pointer;
		transition: background-color 0.3s;
		
		&:hover {
			background-color: #f0f9ff !important;
		}
	}
	
	// 使分页器居中
	.el-pagination {
		margin-top: 20px;
		display: flex;
		justify-content: center;
	}
	
	// 添加搜索结果样式
	.search-result-info {
		margin-bottom: 15px;
		padding: 10px 15px;
		background-color: #f0f9eb;
		border-radius: 4px;
		border-left: 4px solid #67c23a;
		
		.search-keywords {
			display: flex;
			flex-wrap: wrap;
			gap: 10px;
			align-items: center;
			margin-top: 5px;
			
			span {
				background-color: #f0f9eb;
				padding: 4px 8px;
				border-radius: 4px;
				font-size: 14px;
				color: #67c23a;
				
				b {
					color: #f56c6c;
					font-weight: bold;
				}
			}
		}
	}
	
	// 高亮关键词样式
	:deep(.highlight-keyword) {
		color: #409eff;
		font-weight: bold;
		background-color: rgba(64, 158, 255, 0.1);
		padding: 0 2px;
		border-radius: 2px;
	}
	
	// 高亮分类样式
	.highlight-category {
		color: #409eff;
		font-weight: bold;
	}
	
	// 高亮项目样式
	.highlight-item {
		position: relative;
		padding: 2px 5px;
		border-radius: 4px;
		background-color: rgba(103, 194, 58, 0.1);
	}
	
	.bread_view {
		:deep(.breadcrumb) {
			.el-breadcrumb__separator {
			}
			.second_breadcrumb {
				.el-breadcrumb__inner {
				}
			}
		}
	}
	// 分类盒子
	.category_view {
		// 分类item
		.category {
		}
		// item-悬浮
		.category:hover {
		}
		// item-选中
		.categoryActive {
		}
	}

	//搜索
	.list_search {
		min-height: 60px;
		font-size: 22px;
		.search_view {
			.search_label {
				font-size: 22px;
				font-weight: bold;
				margin-right: 8px;
			}
			.search_box {
				:deep(.search_inp), :deep(.el-input__wrapper), :deep(.el-input__inner) {
					font-size: 22px !important;
					height: 48px !important;
					min-width: 260px;
					padding: 0 16px;
				}
				:deep(.search_sel), :deep(.el-select__wrapper), :deep(.el-select__inner) {
					font-size: 22px !important;
					height: 48px !important;
					min-width: 220px;
					padding: 0 16px;
				}
			}
		}
		.search_btn_view {
			.search_btn, .add_btn {
				font-size: 22px;
				height: 48px;
				padding: 0 32px;
				margin-left: 12px;
			}
			.search_btn .el-button__text, .add_btn .el-button__text {
				font-size: 24px !important;
				font-weight: bold;
				line-height: 48px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				display: inline-block;
				vertical-align: middle;
				max-height: 48px;
			}
			:deep(.search_btn span), :deep(.add_btn span) {
				font-size: 20px !important;
				font-weight: 400;
				line-height: 48px;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				display: inline-block;
				vertical-align: middle;
				max-height: 48px;
			}
		}
	}

	// 数据盒子
	.page_list {
		//列表
		.data_box {
			.data_view {
				display: flex;
				flex-direction: column;
				gap: 20px;
				
				.data_item {
					display: flex;
					width: 100%;
					border-radius: 8px;
					background-color: #fff;
					box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
					transition: all 0.3s;
					overflow: hidden;
					
					&:hover {
						transform: translateY(-5px);
						box-shadow: 0 5px 15px 0 rgba(0, 0, 0, 0.15);
					}
					
					.data_img_box {
						width: 180px;
						height: 180px;
						flex-shrink: 0;
						
						.data_img {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
					
					.data_content {
						flex: 1;
						padding: 15px;
						display: flex;
						flex-direction: column;
						
						.data_title1 {
							font-size: 18px;
							font-weight: bold;
							padding: 8px 12px;
							border-radius: 4px;
							background-color: #e6f1fe; /* 浅蓝色背景 */
							color: #409EFF;
							margin-bottom: 10px;
						}
						
						.data_title_phase {
							font-size: 14px;
							margin: 8px 0;
							color: #409EFF;
						}
						
						.data_title2 {
							font-size: 14px;
							margin: 8px 0;
							color: #606266;
						}
						
						.data_title_detail {
							font-size: 14px;
							margin: 8px 0;
							color: #666;
							line-height: 1.6;
							overflow: hidden;
							text-overflow: ellipsis;
							display: -webkit-box;
							-webkit-line-clamp: 2;
							-webkit-box-orient: vertical;
						}
						
						.data_title3 {
							font-size: 14px;
							margin: 8px 0;
							color: #909399;
						}
					}
				}
				
				/* 移除原有的交替样式 */
				.data_item:nth-of-type(2n - 1),
				.data_item:nth-of-type(2n),
				.data_item:nth-of-type(2n - 1):hover,
				.data_item:nth-of-type(2n):hover {
					/* 使用上面定义的统一样式 */
				}
			}
		}
	}

	// 分页器
	.el-pagination {
		// 总页码
		:deep(.el-pagination__total) {
		}
		// 上一页
		:deep(.btn-prev) {
		}
		// 下一页
		:deep(.btn-next) {
		}
		// 上一页禁用
		:deep(.btn-prev:disabled) {
		}
		// 下一页禁用
		:deep(.btn-next:disabled) {
		}
		// 页码
		:deep(.el-pager) {
			// 数字
			.number {
			}
			// 数字悬浮
			.number:hover {
			}
			// 选中
			.number.is-active {
			}
		}
		// sizes
		:deep(.el-pagination__sizes) {
			.el-select {
				//去掉默认样式
				.select-trigger{
					height: 100%;
					.el-input{
						height: 100%;
						.is-focus {
							box-shadow: none !important;
						}
					}
				}
			}
		}
		// 跳页
		:deep(.el-pagination__jump) {
			// 输入框
			.el-input {
				.is-focus {
					box-shadow: none !important;
				}
			}
		}
	}
	
	// 热门信息盒子
	.hot_view {
		// 标题
		.hot_title {
		}

		.hot_list {
			// item
			.hot {
				//图片盒子
				.hot_img_view {
					// 图片
					.hot_img {
					}
				}
				// 内容盒子
				.hot_content {
					// 名称
					.hot_text {
					}
				}
			}
		}
	}
</style>
